import { Socket } from 'socket.io-client';

export default class Chat {
    socket: Socket;
    constructor(socket: Socket) {
        this.socket = socket;
    }
    /**
     * 发送聊天消息
     * @param room
     * @param text
     */
    sendMessage(room: string, text: string) {
        const message = {
            room: room,
            text: text
        };
        this.socket.emit('message', message);
    }

    /**
     * 变更房间
     * @param room 
     */
    changeRoom(room: string) {
        this.socket.emit('join', { newRoom: room });
    }

    /**
     * 处理聊天命令
     * @param input 
     * @returns 
     */
    processCommand(input: string) {
        const words = input.split(' ');
        const command = words[0].substring(1, words[0].length).toLowerCase();
        let message: string | boolean = false;
        switch (command) {
            case 'join':
                words.shift();
                const room = words.join(' ');
                this.changeRoom(room);
                break;
            case 'nick':
                words.shift();
                const name = words.join(' ');
                this.socket.emit('nameAttempt', name);
                break;
            default:
                message = 'Unrecognized command.';
                break;
        }
        return message;
    }
}
